#include "downloadlistitemwidget.h"
#include "ui_downloadlistitemwidget.h"
#include "downloadobject.h"
#include <QFileIconProvider>
#include <QDebug>

DownloadListItemWidget::DownloadListItemWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DownloadListItemWidget)
{
    ui->setupUi(this);
    ui->progressBar->setStyleSheet(DownloadObject::QProgressBarStyle);
    connect(&m_timer,SIGNAL(timeout()),SLOT(updateDownloadSpeed()));
    m_previousSize = 0;
    m_totalSize = 0;
}

DownloadListItemWidget::~DownloadListItemWidget()
{
    delete ui;
}

void DownloadListItemWidget::progressChangeSlot(qint64 r, qint64 total)
{
    ui->progressBar->setRange(0,total);
    ui->progressBar->setValue(r);
}

void DownloadListItemWidget::updateFileInfo(const QString& name, qint64 size)
{
    ui->fileName->setText(QFontMetrics(font()).
                          elidedText(name, Qt::ElideRight, 275));
    ui->fileSize->setText(sizeStandardization(m_totalSize = size));
    QFileIconProvider provider;
    ui->fileTypeIcon->setPixmap(provider.icon(QFileInfo(name)).pixmap(40,40));
}

void DownloadListItemWidget::stateChanged(const QString& statue)
{
    if(statue == tr("D_Downloading"))
        m_timer.start(500);
    else
        m_timer.stop();

    ui->statueLabel->setText(statue);
}

void DownloadListItemWidget::updateDownloadSpeed()
{
    int delta = (ui->progressBar->value() - m_previousSize)*2;
    m_previousSize = ui->progressBar->value();
    ui->downloadSpeed->setText(sizeStandardization(delta) + "/s");

    ui->restOfTime->setText( delta == 0 ? "99:99:99" :
                             timeStandardization((m_totalSize - m_previousSize)/delta + 1));
}

QString DownloadListItemWidget::sizeStandardization(qint64 size)
{
    QString front, back;
    if( size/1024 == 0)
    {
        front =  QString::number(size);
        back = "00";
    }
    else if( size/1024/1024 == 0 && size/1024 > 0)
    {
        front = QString::number(size/1024);
        back = QString::number(size%1024).left(2).rightJustified(2,'0') + "KB";
    }
    else if( size/1024/1024/1024 == 0 && size/1024/1024 > 0)
    {
        front = QString::number(size/1024/1024);
        back = QString::number(size%(1024*1024)).left(2).rightJustified(2,'0') + "M";
    }
    else if( size/1024/1024/1024 > 0)
    {
        front = QString::number(size/1024/1024/1024);
        back = QString::number(size%(1024*1024*1024)).left(2).rightJustified(2,'0') + "T";
    }
    else
        return QString("--");

    return QString("%1.%2").arg(front).arg(back);
}

QString DownloadListItemWidget::timeStandardization(qint64 time)
{
    int h,m,s;

    h = time/3600;
    m = (time%3600)/60;
    s = time%60;

    return QString("%1:%2:%3").arg(QString::number(h).rightJustified(2,'0'))
                              .arg(QString::number(m).rightJustified(2,'0'))
                              .arg(QString::number(s).rightJustified(2,'0'));
}
